using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using UniversalAdminSystem.Infrastructure.Services;

namespace UniversalAdminSystem.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
    private readonly ILogger<TestController> _logger;
    private readonly SpaCyService _spacy;
    private readonly K2ModelService _k2;
    private readonly EmbeddingService _embedding;

    public TestController(ILogger<TestController> logger, K2ModelService k2, SpaCyService spacy, EmbeddingService embedding)
    {
        _logger = logger;
        _k2 = k2;
        _spacy = spacy;
        _embedding = embedding;
    }

    [HttpPost("spacy")]
    public async Task<IActionResult> Spacy([FromBody] SpaCyRequest text)
    {
        // 文本分片
        _logger.LogInformation("开始分片文件: {Text}", text);
        var preprocessResult = await _spacy.AnalyzeTextAsync(text.Text);
        Console.WriteLine(preprocessResult.Entities);
        Console.WriteLine(preprocessResult.Sentences);

        var preprocessResultJson = JsonSerializer.Serialize(preprocessResult, new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        });
        var chunks = await _k2.SendChunkingRequestAsync(preprocessResultJson);
        _logger.LogInformation("分片完成，生成 {Count} 个 chunk", chunks.Count);
        
        // Embedding
        _logger.LogInformation("开始Embedding");
        var embeddings = new List<float[]>();
        embeddings.AddRange(await _embedding.GetEmbeddingAsync(chunks));
        _logger.LogInformation("Embedding 完成: {Count} 个向量", embeddings.Count);
        return Ok(embeddings);
    }
}

public class SpaCyRequest(string text)
{
    public string Text { get; set; } = text;
}